/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */
package com.hopes.bizz.risk.integral.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopes.bizz.risk.common.constant.IntegralDicConstant;
import com.hopes.bizz.risk.integral.dto.RiskIntegralExchangeDTO;
import com.hopes.bizz.risk.integral.dto.RiskIntegralGoodsExcelDTO;
import com.hopes.bizz.risk.integral.entity.RiskIntegralExchangeEntity;
import com.hopes.bizz.risk.integral.entity.RiskIntegralGoodsEntity;
import com.hopes.bizz.risk.integral.entity.RiskIntegralStatisticalEntity;
import com.hopes.bizz.risk.integral.mapper.RiskIntegralGoodsMapper;
import com.hopes.bizz.risk.integral.service.RiskIntegralExchangeAuditRecordService;
import com.hopes.bizz.risk.integral.service.RiskIntegralExchangeService;
import com.hopes.bizz.risk.integral.service.RiskIntegralGoodsService;
import com.hopes.bizz.risk.integral.service.RiskIntegralStatisticalService;
import com.hopes.bizz.risk.integral.vo.RiskIntegralGoodsExcelVO;
import com.hopes.boss.common.core.exception.BizException;
import com.hopes.boss.common.entity.ValidateImportBO;
import com.hopes.boss.common.excel.vo.ErrorMessage;
import com.hopes.boss.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;

/**
 * 积分商品管理
 *
 * @author liujiaqi
 * @date 2023-07-25 14:39:19
 */
@Service
@RequiredArgsConstructor
public class RiskIntegralGoodsServiceImpl extends ServiceImpl<RiskIntegralGoodsMapper, RiskIntegralGoodsEntity> implements RiskIntegralGoodsService {

    private final RiskIntegralExchangeService riskIntegralExchangeService;
    private final RiskIntegralStatisticalService riskIntegralStatisticalService;
    private final RiskIntegralExchangeAuditRecordService riskIntegralExchangeAuditRecordService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean exchange(RiskIntegralExchangeDTO riskIntegralExchangeDTO) {
        Assert.notNull(riskIntegralExchangeDTO.getGoodsId(), "兑换商品不可为空");
        final RiskIntegralGoodsEntity integralGoods = baseMapper.selectById(riskIntegralExchangeDTO.getGoodsId());
        if (Objects.isNull(integralGoods)) {
            throw new BizException("兑换商品不存在！");
        }
        // 1、判断商品库存是否足够
        final Integer quantityNumber = Optional.ofNullable(integralGoods.getQuantityNumber()).orElse(0);
        if (riskIntegralExchangeDTO.getAmount() > quantityNumber) {
            throw new BizException("商品余量不足，当前商品数量：" + quantityNumber);
        }

        // 2、判断当前用户积分是否充足
        final RiskIntegralStatisticalEntity riskIntegralStatistical = riskIntegralStatisticalService.lambdaQuery()
                .eq(RiskIntegralStatisticalEntity::getAccountId, SecurityUtils.getUserId())
                .one();
        if (Objects.isNull(riskIntegralStatistical)) {
            throw new BizException("当前账户无积分");
        }
        final int totalIntegral = riskIntegralExchangeDTO.getAmount() * integralGoods.getExchangeIntegral();
        if (riskIntegralStatistical.getExchangeableIntegral() < totalIntegral) {
            throw new BizException("当前账户积分不足，账户可兑换积分：" + riskIntegralStatistical.getExchangeableIntegral());
        }
        // 3、更新商品数量
        integralGoods.setQuantityNumber(quantityNumber - riskIntegralExchangeDTO.getAmount());
        updateById(integralGoods);

        // 4、更新用户积分
        riskIntegralStatistical.setExchangeableIntegral(riskIntegralStatistical.getExchangeableIntegral() - totalIntegral);
        riskIntegralStatisticalService.updateById(riskIntegralStatistical);

        // 5、保存兑换记录
        final Date date = Calendar.getInstance().getTime();
        final RiskIntegralExchangeEntity riskIntegralExchangeEntity = new RiskIntegralExchangeEntity();
        riskIntegralExchangeEntity.setExchangeTime(date);
        riskIntegralExchangeEntity.setAccountId(SecurityUtils.getUser().getId());
        riskIntegralExchangeEntity.setAmount(riskIntegralExchangeDTO.getAmount());
        riskIntegralExchangeEntity.setGoodsId(riskIntegralExchangeDTO.getGoodsId());
        riskIntegralExchangeEntity.setGoodsName(integralGoods.getGoodsName());
        riskIntegralExchangeEntity.setConfirmStatus(IntegralDicConstant.INTEGRAL_GOODS_CONFIRM_STATUS_WAIT);
        riskIntegralExchangeEntity.setIssueStatus(IntegralDicConstant.INTEGRAL_GOODS_ISSUE_STATUS_NOT_ISSUED);
        riskIntegralExchangeEntity.setAuditStatus(IntegralDicConstant.INTEGRAL_GOODS_AUDIT_STATUS_WAIT);
        riskIntegralExchangeService.save(riskIntegralExchangeEntity);
        // 6、 提交工作流任务
        riskIntegralExchangeService.submit(riskIntegralExchangeEntity.getId());
        return true;
    }




    @Override
    public ValidateImportBO<RiskIntegralGoodsExcelDTO> validateImport(List<RiskIntegralGoodsExcelDTO> excelDTOList) {
        ValidateImportBO<RiskIntegralGoodsExcelDTO> bo = new ValidateImportBO<>();
        List<ErrorMessage> errorMessageList = new ArrayList<>();
        List<RiskIntegralGoodsExcelDTO> saveList = new ArrayList<>(excelDTOList);
        int successNum = excelDTOList.size();
        int failedNum = 0;

        bo.setErrorMessages(errorMessageList);
        bo.setSaveList(saveList);
        bo.setSuccessNum(successNum);
        bo.setFailedNum(failedNum);
        return bo;
    }

    @Override
    public RiskIntegralGoodsEntity importDtoToEntity(RiskIntegralGoodsExcelDTO excelDto) {
        RiskIntegralGoodsEntity entity = new RiskIntegralGoodsEntity();
        BeanUtils.copyProperties(excelDto, entity);
        return entity;
    }

    @Override
    public RiskIntegralGoodsExcelVO exportEntityToVo(RiskIntegralGoodsEntity entity) {
        RiskIntegralGoodsExcelVO excelVO = new RiskIntegralGoodsExcelVO();
        BeanUtils.copyProperties(entity, excelVO);
        return excelVO;
    }
}
